<template>
  <div>
    <el-card shadow="hover">
      <el-button
        type="primary"
        :icon="Plus"
        @click="showTrademarkDialog({ id: 0, tmName: '', logoUrl: '' })"
      >
        添加
      </el-button>
      <el-table
        border
        v-loading="loading"
        :data="trademarkList"
        class="trademark__table"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <template #default="scope">
            <div>
              <img
                class="pic"
                :src="scope.row.logoUrl"
                :alt="scope.row.tmName"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              :icon="Edit"
              size="small"
              type="warning"
              @click="showTrademarkDialog(scope.row)"
            />
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="open(scope.row.tmName, scope.row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :total="total"
        :page-sizes="[3, 6, 9, 12]"
        v-model:page-size="pageSize"
        v-model:current-page="currentPage"
        @size-change="getTrademark"
        @current-change="getTrademark"
        layout="prev, pager, next, jumper, -> , sizes, total"
      />
    </el-card>
    <el-dialog
      v-model="dialogFormVisible"
      :title="`${formData.id ? '修改' : '添加'}品牌`"
    >
      <el-form
        ref="formRef"
        :rules="formRules"
        :model="formData"
        label-width="100px"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input placeholder="请输入品牌名称" v-model="formData.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            :show-file-list="false"
            class="avatar-uploader"
            accept="image/jpeg, image/png"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :action="`${BASE_URL}/admin/product/fileUpload`"
          >
            <img
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过200kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: "TradeMark",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  getTrademarkList,
  removeTrademark,
  addTrademark,
  updateTrademark,
} from "@/api/product/trademark";
import type {
  TrademarkList,
  TrademarkItem,
} from "@/api/product/model/trademarkModel";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
/******************************定义from的三兄弟********************************/
// 获取表单的DOM
const formRef = ref();
// 制定校验表单的规则
const formRules = reactive({
  tmName: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度必须在2到10个字符之间", trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "请上传图片" }],
});
// 初始化表单的数据
const formData = reactive({
  id: 0,
  logoUrl: "",
  tmName: "",
});
/*****************************(添加或修改)对话框提交品牌功能********************************/
const submit = async () => {
  // 对表单进行校验
  await formRef.value.validate();
  // 如果有id则为更新品牌的请求
  if (formData.id) {
    await updateTrademark(formData);
  }
  // 如果没有id则为添加品牌的请求
  else {
    await addTrademark(formData);
  }
  // 关闭对话框
  dialogFormVisible.value = false;
  // 提示用户
  ElMessage.success(`${formData.id ? "修改" : "添加"}品牌成功`);
  // 刷新页面
  getTrademark();
};
/*******************************upload组件相关**********************************/
// 显示或隐藏对话框，默认为隐藏
const dialogFormVisible = ref(false);
// 根据不同的运行环境配置不同的前缀
const BASE_URL = import.meta.env.VITE_API_URL;
// 🐷 此处为了提高复用性 点击添加按钮
// const showAddTrademarkDialog = (trademarkItem: TrademarkItem) => {
//   // 点击添加之前先清除表单内容
//   formData.id = trademarkItem.id;
//   formData.logoUrl = trademarkItem.logoUrl;
//   formData.tmName = trademarkItem.tmName;
//   // 当表单校验失败时，即使关闭对话框(虽然会清空表单内容，但校验失败的消息仍不会清除)
//   // 调用清除整个表单校验规则的API
//   // formRef.value.clearValidate();
//   // 当第一次渲染的时候，不去点击对话框，对话框是不会渲染的，
//   // 相应的表单也不会渲染，因此无法拿到表单的实例对象
//   // Cannot read properties of undefined (reading 'clearValidate')
//   // 在value后加一个?
//   formRef.value?.clearValidate();
//   // 展示对话框
//   dialogFormVisible.value = true;
// };
// 点击编辑按钮
// const showUpdateTrademarkDialog = (trademarkItem: TrademarkItem) => {
//   // 将每一行的数据赋值给formData相应的属性名
//   formData.id = trademarkItem.id;
//   formData.logoUrl = trademarkItem.logoUrl;
//   formData.tmName = trademarkItem.tmName;
//   formRef.value?.clearValidate();
//   // 显示对话框
//   dialogFormVisible.value = true;
// };

// 点击添加或者编辑按钮
const showTrademarkDialog = (trademarkItem: TrademarkItem) => {
  // 将每一行的数据赋值给formData相应的属性名
  formData.id = trademarkItem.id;
  formData.logoUrl = trademarkItem.logoUrl;
  formData.tmName = trademarkItem.tmName;
  formRef.value?.clearValidate();
  // 显示对话框
  dialogFormVisible.value = true;
};
// 图片上传成功之后触发的函数
// response为成功后服务器响应的结果
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  // 将服务器返回的date(即url)赋值给formData
  formData.logoUrl = response.data;
  // 若服务器已将成功返回了数据，则说明一定校验通过，此时清除logoUrl的校验规则
  formRef.value.clearValidate(["logoUrl"]);
};
// 图片上传之前触发的函数
// 通常在此处校验图片的格式和大小 返回值为false则不上传图片 返回值为true则上传图片
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 校验图片的类型
  const typeList = ["image/jpeg", "image/png"];
  if (!typeList.includes(rawFile.type)) {
    ElMessage.error("上传图片只能是jpg或png格式!");
    return false;
  }
  //校验图片的大小
  else if (rawFile.size / 1024 > 200) {
    ElMessage.error("图片大小不能超过200KB!");
    return false;
  }
  return true;
};
/*****************************分页器相关*******************************/
const total = ref(0);
const pageSize = ref(3);
const currentPage = ref(1);
const loading = ref(false);
const trademarkList = ref<TrademarkList>([]);
/************************封装一个发送请求的函数**************************/
async function getTrademark() {
  // 展示加载页
  loading.value = true;
  // 发送请求获取数据
  const res = await getTrademarkList(currentPage.value, pageSize.value);
  trademarkList.value = res.records;
  total.value = res.total;
  // 隐藏加载页
  loading.value = false;
}
// 挂载生命周期钩子函数
onMounted(() => {
  getTrademark();
  ElMessage.success("获取品牌分页列表成功");
});
/*****************************删除按钮部分*****************************/
const open = (trademarkName: string, id: number) => {
  ElMessageBox.confirm(`确定删除 ${trademarkName} 吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await removeTrademark(id);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      getTrademark();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
</script>

<style lang="scss" scoped>
.trademark__table {
  margin: 20px 0;
}
.pic {
  width: 100px;
  height: 60px;
}
.avatar-uploader {
  :deep() {
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
